<?php

namespace app\common\model;

use think\facade\Cache;
use think\model;

class Base extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    //protected $createTime = 'created_at';
    //protected $updateTime = 'updated_at';

    /**
     * 模型字段
     * @return array
     */
    public static function allowFields(): array
    {
        return array_keys((new static)->schema);
    }

    /**
     * 通用添加
     * @param array $data
     * @return \think\response\Json
     */
    public static function assignSave(array $data)
    {
        self::create($data);
        return json(['code' => 0, 'message' => '添加成功']);
    }

    /**
     * 通用修改
     * @param array $data
     * @return \think\response\Json
     */
    public static function assignUpdate(array $data)
    {
        $result = self::where('id', $data['id'])->update($data);
        if ($result) {
            return json(['code' => 0, 'message' => '修改成功']);
        } else {
            return json(['code' => 1, 'message' => '修改失败']);
        }
    }

    /**
     * 通用删除
     * @param int|string $id
     * @return \think\response\Json
     */
    public static function assignDelete($id)
    {
        $id = explode(',', $id);
        $result = self::destroy($id);
        if ($result) {
            return json(['code' => 0, 'message' => '删除成功']);
        } else {
            return json(['code' => 1, 'message' => '删除失败']);
        }
    }
}
